package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.RedisConstant;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.mapper.admin.CategoryMapper;
import com.sky.pojo.Category;
import com.sky.result.PageResult;
import com.sky.service.admin.CategoryService;
import com.sky.utils.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public PageResult listByPage(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        List<Category> categoryList = categoryMapper.findByPage(categoryPageQueryDTO);
        Page<Category> pageObj = (Page<Category>) categoryList;
        return new PageResult(pageObj.getTotal(), pageObj.getResult());
    }

    @Override
    public void update(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        Long empId = ThreadLocalUtils.getLoginEmpId();
        category.setUpdateUser(empId);
        categoryMapper.update(category);
    }

    @Override
    public void delete(Integer id) {
        //TODO 类别里面有菜品的不能删除
        categoryMapper.delete(id);
    }

    @Override
    public void insert(Category category) {
        category.setCreateTime(LocalDateTime.now());
        Long empId = ThreadLocalUtils.getLoginEmpId();
        category.setCreateUser(empId);
        categoryMapper.insert(category);
    }

    @Override
    public List<Category> ListByType(Integer type) {
        List<Category> list = (List<Category>) redisTemplate.opsForValue().get(RedisConstant.CATEGORY_LIST + type);
        if (list==null||list.size()==0){
             list = categoryMapper.listByType(type);
             redisTemplate.opsForValue().set(RedisConstant.CATEGORY_LIST+type,list);
        }
        return list;
    }
}
